package com.son.hotel.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.son.hotel.common.ErrorCode;
import com.son.hotel.common.Result;
import com.son.hotel.domain.AccommodationInfo;
import com.son.hotel.domain.Customers;
import com.son.hotel.domain.RoomType;
import com.son.hotel.domain.Rooms;
import com.son.hotel.execption.BusinessException;
import com.son.hotel.mapper.AccommodationInfoMapper;
import com.son.hotel.response.CustomerAndAccommodationResp;
import com.son.hotel.response.CustomerAndRoomInfoResp;
import com.son.hotel.response.RoomAccountResp;
import com.son.hotel.service.AccommodationInfoService;
import com.son.hotel.service.RoomTypeService;
import com.son.hotel.service.RoomsService;
import com.son.hotel.vo.CustomAndRoomInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class AccommodationInfoServiceImpl extends ServiceImpl<AccommodationInfoMapper, AccommodationInfo>
implements AccommodationInfoService {

    @Autowired
    private RoomsService roomsService;

    @Autowired
    private RoomsServiceImpl roomsServiceImpl;

    @Autowired
    private AccommodationInfoMapper accommodationInfoMapper;

    @Autowired
    private CustomersServiceImpl customersService;

    @Autowired
    private RoomTypeService roomTypeService;

    @Override
    public void addAccommodationInfo(CustomAndRoomInfo customAndRoomInfo) {
        //计算住宿时长
        DateTime startTime = DateUtil.parse(customAndRoomInfo.getStartTime(), "yyyy-MM-dd");
        DateTime endTime = DateUtil.parse(customAndRoomInfo.getEndTime(), "yyyy-MM-dd");
        int duration = (int)DateUtil.between(startTime, endTime, DateUnit.DAY);
        //计算住宿费用
        int price = customAndRoomInfo.getPrice();
        int cost = price * duration;
        //TODO 根据typeId查询room表获取具体房间号并更改status为1
        QueryWrapper<Rooms> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("typeId",customAndRoomInfo.getTypeId());
        //查询status为0的房间
        queryWrapper.eq("status",0);
        //按升序排序
        queryWrapper.orderByAsc("id");
        //只限制查出一条数据
        queryWrapper.last("limit 1");
        //查出一条room信息
        Rooms room = roomsService.getOne(queryWrapper);
        log.info("room:{}",room);
        //更改房间的status
        roomsServiceImpl.updateRoomStatus(room);
        //TODO 将数据插入住房信息表
        Integer roomId = room.getId();
        //根据身份证获取用户信息
        Customers customer = customersService.getCustomerByIdentity(customAndRoomInfo.getIdentity());
        Integer customerId = customer.getId();
        AccommodationInfo accommodationInfo = new AccommodationInfo();
        accommodationInfo.setCost(cost);
        accommodationInfo.setDuration(duration);
        accommodationInfo.setCustomerId(customerId);
        accommodationInfo.setRoomId(roomId);
        accommodationInfo.setInDate(startTime);
        accommodationInfo.setOutDate(endTime);
        int insert = accommodationInfoMapper.insert(accommodationInfo);
        if (insert <= 0){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"插入失败");
        }
        //TODO 让房间数量减一
        UpdateWrapper<RoomType> wrapper = new UpdateWrapper<>();
        wrapper.setSql("quantity = quantity - 1").eq("id",customAndRoomInfo.getTypeId());
        boolean result = roomTypeService.update(wrapper);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"修改错误");
        }
    }

    /**
     * 向住房信息表中插入数据
     * @param customerAndRoomInfoResp
     */
    public void addAccommodationInfo(CustomerAndRoomInfoResp customerAndRoomInfoResp){
        AccommodationInfo accommodationInfo = new AccommodationInfo();
        //计算住宿时长
        DateTime startTime = DateUtil.parse(customerAndRoomInfoResp.getStartTime(), "yyyy-MM-dd");
        DateTime endTime = DateUtil.parse(customerAndRoomInfoResp.getEndTime(), "yyyy-MM-dd");
        int duration = (int)DateUtil.between(startTime, endTime, DateUnit.DAY);
        //计算花费
        int newRoomId = customerAndRoomInfoResp.getNewRoomId();
        Rooms rooms = roomsService.getById(newRoomId);
        Integer typeId = rooms.getTypeId();
        RoomType roomType = roomTypeService.getById(typeId);
        Integer price = roomType.getPrice();
        int cost = price * duration;

        accommodationInfo.setCost(cost);
        accommodationInfo.setDuration(duration);
        accommodationInfo.setCustomerId(customerAndRoomInfoResp.getId());
        accommodationInfo.setRoomId(newRoomId);
        accommodationInfo.setInDate(Convert.toDate(customerAndRoomInfoResp.getStartTime()));
        accommodationInfo.setOutDate(Convert.toDate(customerAndRoomInfoResp.getEndTime()));

        this.save(accommodationInfo);
    }

    @Override
    public List<CustomerAndRoomInfoResp> listCustomerAndRoomInfo(List<AccommodationInfo> list) {
        List<CustomerAndRoomInfoResp> customerAndRoomList = new ArrayList<>();
        for (AccommodationInfo accommodationInfo : list) {
            CustomerAndRoomInfoResp customerAndRoomInfoResp = new CustomerAndRoomInfoResp();
            Integer customerId = accommodationInfo.getCustomerId();
            Integer roomId = accommodationInfo.getRoomId();
            //获取customer具体信息
            Customers customer = customersService.getById(customerId);
            String phone = customer.getPhone();
            String name = customer.getName();
            String identity = customer.getIdentity();
            //装载信息
            customerAndRoomInfoResp.setId(customerId);
            customerAndRoomInfoResp.setPhone(phone);
            customerAndRoomInfoResp.setName(name);
            customerAndRoomInfoResp.setNewRoomId(roomId);
            customerAndRoomInfoResp.setIdentity(identity);
            customerAndRoomInfoResp.setCost(accommodationInfo.getCost());
            customerAndRoomInfoResp.setStartTime(Convert.toStr(accommodationInfo.getInDate()));
            customerAndRoomInfoResp.setEndTime(Convert.toStr(accommodationInfo.getOutDate()));
            //装载列表
            customerAndRoomList.add(customerAndRoomInfoResp);
        }
        return customerAndRoomList;
    }

    @Override
    public List<RoomAccountResp> listRoomAccount(int year,int month) {
        //处理日期参数year = 2025 month = 6  =>startTime = 2025-6-1 endTime = 2025-7-1
        LocalDate start = LocalDate.of(year, month, 1);
        LocalDate end = start.plusMonths(1);

        Date startTime = Convert.toDate(start);
        Date endTime = Convert.toDate(end);

        //调用Mapper层
        List<RoomAccountResp> roomAccountResp = accommodationInfoMapper.listRoomAccount(startTime, endTime);
        log.info("住房信息统计:{}",roomAccountResp);
        return roomAccountResp;
    }


}
